const fs = require('fs')
const { Transform }  = require('stream')

// series串行，按顺序依次执行；parallel并行，同步执行
const { series, parallel } = require('gulp')

// 4.0以前的写法
// gulp.task('bar', done => {
//   console.log('bar working')
//   done()
// })

exports.foo = done => {
  console.log('foo task working')
  done() // 标识任务完成
}

// 默认任务
exports.default = done => {
  console.log('default task working~')
  done()
}

/**
 * gulp异步任务
 */

// 错误回调函数，抛出错误阻止后面的任务继续执行
exports.callback_error = done => {
  console.log('callback task error')
  done(new Error('task failed'))
}

// 使用promise代替done
exports.promise = () => {
  console.log('promise task')
  return Promise.resolve()
}
exports.promise_error = () => {
  console.log('promise task error')
  return Promise.reject(new Error('task failed'))
}

// 使用async await
// exports.async = async () => {
//   await fn()
//   console.log('async task')
// }

// 使用stream流
exports.stream = () => {
  const readStream = fs.createReadStream('package.json')
  const writeStream = fs.createWriteStream('temp.txt')
  readStream.pipe(writeStream)
  return readStream;
}
// exports.stream = done => {
//   const readStream = fs.createReadStream('package.json')
//   const writeStream = fs.createWriteStream('temp.txt')
//   readStream.pipe(writeStream)
//   readStream.on('end', () => {
//     done()
//   })
// }
exports.minStream = () => {
  const read = fs.createReadStream('package.json')
  const write = fs.createWriteStream('temp.txt')
  const transform = new Transform({
    transform: (chunk, encoding, callback) => {
      const input = chunk.toString()
      const output = input.replace(/\s+/g, '').replace(/\/\*.+?\*\//g, '')
      callback(null, output)
    }
  })
  read
    .pipe(transform)
    .pipe(write)
  return read
}
